/**
* @author Ucar Sahin
*
* 31.05.2011
* LoginServiceImpl.java
* 
*/

package at.fhv.easyDietWeb.server;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import at.fhv.easyDietWeb.client.loginService.ILoginService;
import at.fhv.easyDietWeb.server.controller.DatabaseController;
import at.fhv.easyDietWeb.server.controller.useCase.UserLogInController;
import at.fhv.easyDietWeb.shared.db.masterData.Patient;
import at.fhv.easyDietWeb.shared.db.masterData.User;
import at.fhv.easyDietWeb.shared.exception.database.NoSearchResultException;
import at.fhv.easyDietWeb.shared.exception.database.UserIsNoPatientException;
import at.fhv.easyDietWeb.shared.exception.useCase.InvalidLoginException;
import at.fhv.easyDietWeb.shared.util.ISessionAttributes;
import at.fhv.easyDietWeb.shared.util.wrappers.UserWrapper;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

/**
 * Servlet which implements the loginService interface
 * @author Sahin
 *
 */
public class LoginServiceImpl extends RemoteServiceServlet
	implements ILoginService
{
	private HttpSession session;
	
	/**
	 * gwt insists on a default constructor
	 */
	public LoginServiceImpl(){}
	
	@Override
	public UserWrapper validateLogin(String username, String pwd)
	{			
		UserLogInController ulic = new UserLogInController();
				
		User user = null;
		UserWrapper userW = null;
		
		try
		{
			user = ulic.getUser(username, pwd);
			
			try
			{
				Patient p = DatabaseController.getInstance().getPatient(user);
				userW = new UserWrapper(p.getPatientId(), p.getFirstName(), p.getLastName());
				
				session.setAttribute(ISessionAttributes.USER_ATTR, userW);
			} 
			catch (NoSearchResultException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			} 
			catch (UserIsNoPatientException e)
			{
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} 
		catch (InvalidLoginException e)
		{
			return null;
		}
		
		return userW;		
	}
	
	public UserWrapper checkSession()
	{
		HttpServletRequest request = this.getThreadLocalRequest();
		session = request.getSession();
		
		return (UserWrapper) session.getAttribute(ISessionAttributes.USER_ATTR);
	}
}